import Layout from '@/views/layout/Layout'
import Empty from '@/views/layout/empty'
import AsyncComponent from '@/components/AsyncComponent.vue'
import store from '@/store'

export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

export function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (const k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            const str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
        }
    }
    return fmt
}

export function addMonth(d, m) {
    var ds = d.split('-')
    var _d = ds[2] - 0
    var nextM = new Date(ds[0], ds[1] - 1 + m + 1, 0)
    var max = nextM.getDate()
    d = new Date(ds[0], ds[1] - 1 + m, _d > max ? max : _d)
    return d.toLocaleDateString().match(/\d+/g).join('-')
}

function padLeftZero(str) {
    return ('00' + str).substr(str.length)
}

export function formatTime(time, option) {
    time = +time * 1000
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
    // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
        )
    }
}

export const pickerOptions = [
    {
        text: '今天',
        onClick(picker) {
            const end = new Date()
            const start = new Date(new Date().toDateString())
            end.setTime(start.getTime())
            picker.$emit('pick', [start, end])
        }
    },
    {
        text: '最近一周',
        onClick(picker) {
            const end = new Date(new Date().toDateString())
            const start = new Date()
            start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
        }
    },
    {
        text: '最近一个月',
        onClick(picker) {
            const end = new Date(new Date().toDateString())
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
        }
    },
    {
        text: '最近三个月',
        onClick(picker) {
            const end = new Date(new Date().toDateString())
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
        }
    }
]

export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function() {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function(...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}

export function isExternal(path) {
    return /^(https?:|mailto:|tel:)/.test(path)
}

const componentsMap = {
    // PER_FAMILY: () => import('@/views/form/EMPAUTONOMY/self_EMP/self_empBack/self_Family_list.vue')
}

function generateRouter(item, num) {
    // if (num === 3) {
    //     componentsMap[item.menuCode] = function() {
    //         return import(`@/views${item.menuVueUrl}`)
    //     }
    // }
    var routerItem = {
        // path: num === 3 ? item.menuVueUrl.replace('.vue', '') : `${item.menuCode}`,
        path: `/asyncForm/${item.menuId}`,
        name: item.menuCode,
        meta: {
            title: item.menuName,
            icon: item.menuIcon
        },
        // component: num === 1 ? Layout : num === 2 ? Empty : componentsMap[item.menuCode],
        component: AsyncComponent,
        children: []
    }
    return routerItem
}

export function parseRouters(arr) {
    const asynRrouter = []
    const arrList = new Set()
    store.getters.allPathList.map(x => arrList.add(x))
    arr.forEach(element => {
        const tpl1 = generateRouter(element, 1)
        arrList.add(tpl1.path)
        element.childrens.forEach((el2, index) => {
            const tpl2 = generateRouter(el2, 2)
            arrList.add(tpl2.path)
            if (el2.childrens) {
                el2.childrens.forEach(el3 => {
                    const tpl3 = generateRouter(el3, 3)
                    arrList.add(tpl3.path)
                    tpl2.children.push(tpl3)
                })
            }
            tpl1.children.push(tpl2)
        })
        asynRrouter.push(tpl1)
    })
    // 把所有路径传回vuex
    // const allPath = Array.from(arrList)
    // console.log(allPath)
    // store.commit('SET_ALLPATH', allPath)
    return asynRrouter
}

export const columnType = {
    '1': { 'text': '文本框', 'handsontable': 'text' },
    '2': { 'text': '下拉列表选择', 'handsontable': 'dropdown' },
    '3': { 'text': '单选框组', 'handsontable': 'text' },
    '4': { 'text': '复选框组', 'handsontable': 'text' },
    '5': { 'text': '复选框', 'handsontable': 'text' },
    '6': { 'text': '日期选择框', 'handsontable': 'date' },
    '7': { 'text': 'lookup弹出窗', 'handsontable': 'text' },
    '8': { 'text': '多行文本域', 'handsontable': 'text' },
    '9': { 'text': '附件', 'handsontable': 'text' },
    '10': { 'text': '富文本', 'handsontable': 'text' },
    '11': { 'text': '下拉树选择', 'handsontable': 'text' },
    '12': { 'text': '模糊匹配输入框', 'handsontable': 'text' }}

export const loadJs = (url) => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.type = 'text/javascript'
        document.body.appendChild(script)
        script.onload = () => {
            resolve()
        }
    })
}

export const loadCss = (url) => {
    return new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        document.head.appendChild(link)
        link.onload = () => {
            resolve()
        }
    })
}

export const generateUUID = () => {
    var d = new Date().getTime()
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16)
    })
    return uuid
}

// 匹配参数 如[p:userid]
export function getFmParam(sUrl, query) {
    let temp = sUrl
    sUrl.replace(/\[(\w+):(\w+)\]?/g, function(str, key, value) {
        console.log(str, key, value)
        let tempFormatValue = ''
        switch (key) {
            case 'p':
                tempFormatValue = query[value] || ''
                break
            case 'c':
                switch (value) {
                    case 'timestamp':
                        tempFormatValue = new Date().getTime()
                        break
                    case 'date':
                        tempFormatValue = formatDate(new Date(), 'yyyy-mm-dd')
                        break
                    case 'datetime':
                        tempFormatValue = formatDate(new Date(), 'yyyy-mm-dd hh:ii:ss')
                        break
                    default:
                        break
                }
                break
            default:
                break
        }
        console.log(tempFormatValue)
        temp = temp.replace(str, tempFormatValue)
    })
    console.log('~~~~~~~~~~~~~~')
    console.log(temp)
    return temp
}
